/*
* jQuery FillOptions
* ajax填充插件FillOptions，这个插件可以通过ajax方法获取数据并把数据添加到下拉列表框，数据格式支持xml格式和json格式，插件定义如下
 FillOptions(url,options)
 参数说明
 url：ajax请求的地址，必须

 options包括如下参数
    datatype：ajax请求返回的数据格式,可以是”xml”或”json”，默认为”json”
    textfield：ajax请求返回的数据中下拉列表框选项文本的字段，默认为”text”
    valuefiled：ajax请求返回的数据中下拉列表框选项值的字段，默认为”value”
    keepold：布尔类型，是否保留下拉列表框选项原有选项，默认为不保留
    selected：数值型，填充选项后第几项为选中状态，默认为0
*/

jQuery.fn.FillOptions = function(url,options){
    if(url.length == 0) throw "request is required";
    var text = options.textfield || "text";
    var value = options.valuefiled || "value";
    var type = options.datatype.toLowerCase() || "json";
    if(type != "xml")type="json";
    var keep = options.keepold?true:false;
    var isSelected = options.isSelected || "isSelected";
    var isDisabled = options.isDisabled || "isDisabled";

    $.ajaxSetup({async:true});
    var datas;
    var thisObj = this;
    var selectVals=new Array();
    if(type == "xml")
    {
        $.get(url,function(xml){
            datas=xml;
            thisObj.each(function(){
                if(this.tagName == "SELECT")
                {
                    var select = this;
                    if(!keep)$(select).html("");
                    $(text,datas).each(function(i){
                        option = new Option($(this).text(),$($(value,datas)[i]).text());
                        if(eval("n."+isDisabled)==1)option.disabled=true;
                        select.options.add(option);
                        if(eval("n."+isSelected)==1)selectVals.push($($(value,datas)[i]).text());
                    });
                }
            });
            if(options.callback != undefined){
                options.callback(datas,selectVals);
            }
        });
    }
    else
    {
        $.getJSON(url,function(json){
            if(json!=undefined && json!=""){
                datas=json;
                thisObj.each(function(){
                    if(this.tagName == "SELECT")
                    {
                        var select = this;
                        if(!keep)$(select).html("");
                        $.each(datas,function(i,n){
                            option = new Option(eval("n."+text),eval("n."+value));
                            if(eval("n."+isDisabled)==1)option.disabled=true;
                            select.options.add(option);
                            if(eval("n."+isSelected)==1)selectVals.push(eval("n."+value));
                        });
                    }
                });
                if(options.callback != undefined){
                    options.callback(datas,selectVals);
                }
            }
            if(json==undefined || json==""){
                if(options.callback != undefined){
                    options.callback();
                }
            }

        });
    }
};